public without sharing class ContractChangeHandler {


    public ContractChangeHandler(){
      
         
    }
    /*///合同变更审批通过之后 回写到合同变更
    webservice static String resertContractProduct(String ccId) {
        
        List<ContractChangeList__c> cclList =[select Id, AdjustPrice__c,AddProduct__c,DelProduct__c,ContractProduct__c, 
            Product__c,AdjustSalesPrice__c,SalesPrice__c,ContactChange__c,ContactChange__r.Contact__c,Product__r.Name,
            Product__r.Category1__c,ContactChange__r.Contact__r.CompanyControls__c,DiscountRate__c
         from ContractChangeList__c where ContactChange__c =:ccId ]; 


         Map<Id,Id> addMap = new Map<Id,Id>();
         Set<String> companys = new Set<String>();
         for ( ContractChangeList__c ccl : cclList) {
            if (ccl.AddProduct__c == true ) {
                addMap.put(ccl.Product__c,ccl.ContactChange__r.Contact__c);
                companys.add(ccl.ContactChange__r.Contact__r.CompanyControls__c);
            }
         }

         ///查询价格
         Map<Id,Price__c> priceMap = getPriceMap(addMap.keySet(),companys);

        ///新增
        List<ContractProduct__c>cclNewList = new List<ContractProduct__c>();
        ///删除
        List<ContractProduct__c>cclDelList = new List<ContractProduct__c>();

        ///调价
        List<ContractProduct__c>cclAdjustList = new List<ContractProduct__c>();
                   
       Id rt  = Utils.getRecordTypeIdByDevNameAndObjName('ContractCommodityProduct','ContractProduct__c');                                   
        ///查询 合同变更明细
        for (ContractChangeList__c ccl:cclList) {
             if (ccl.AddProduct__c == true) {
                 ContractProduct__c cp = new ContractProduct__c(
                    Name = ccl.Product__r.Name,
                    Product__c = ccl.Product__c,
                    AreaDealerPrice__c = priceMap.containsKey(ccl.Product__c) ? priceMap.get(ccl.Product__c).AreaDealerPrice__c : 0,
                    InvoiceDealerPrice__c = priceMap.containsKey(ccl.Product__c) ? priceMap.get(ccl.Product__c).InvoiceDealerPrice__c : 0,
                    UnitPrice1__c = priceMap.containsKey(ccl.Product__c) ? priceMap.get(ccl.Product__c).MarketPrice__c : 0,//市场报价
                    SalesPrice__c =ccl.SalesPrice__c,
                    Taxrate__c =priceMap.containsKey(ccl.Product__c) ? priceMap.get(ccl.Product__c).Taxrate__c : null ,
                    Contract__c = ccl.ContactChange__r.Contact__c,
                    ProductLine__c = ccl.Product__r.Category1__c,
                    RecordTypeId = rt,
                    DiscountRate__c =  ccl.DiscountRate__c,
                    IsSycToNc__c = false

                 );
                 cclNewList.add(cp);
             }

             if (ccl.AdjustPrice__c == true) {
                 ContractProduct__c cp = new ContractProduct__c(
                    Id = ccl.ContractProduct__c,
                    SalesPrice__c = ccl.AdjustSalesPrice__c,
                    IsSycToNc__c = false

                 );
                 cclAdjustList.add(cp);
             }

             if (ccl.DelProduct__c == true) {
                  ContractProduct__c cp = new ContractProduct__c(
                    Id = ccl.ContractProduct__c

                 );
                  cclDelList.add(cp);
             }  
         } 
         SavePoint sp = Database.setSavepoint();
         try {
           if (cclNewList.size() > 0) insert cclNewList;
            if (cclDelList.size() >0) delete cclDelList;
            if (cclAdjustList.size() > 0) update cclAdjustList; 
            return 'ok'; 
         }catch (Exception e) {
            Database.rollback(sp); 
            return e.getMessage();
         }
         
         


    }
     private static Map<Id,Price__c> getPriceMap(Set<Id> pids ,Set<String>coms){
        Map<Id, Price__c> priceMap = new Map<Id, Price__c>();
            for (Price__c pr : [select Id, Product__c,Product__r.bggsjhdj__c, MarketPrice__c, HospitalManagerPrice__c, HospitalBottomPrice__c, CompanyBottomPrice__c,
                AreaDealerPrice__c, InvoiceDealerPrice__c, RepairCost__c, InstCost__c ,LastMonthAveragePrice__c,Taxrate__c  
                                from Price__c where Product__c in : pids and Company__c in:coms]) {
                priceMap.put(pr.Product__c, pr);
            }
      return priceMap;
  
  }
*/
/*
    
	///合同变更审批通过之后 回写到合同产品  如果是分支机构  还要将其 反写到总部的合同产品
   ///合同变更审批通过之后 回写到合同变更
    public static void resertContractProduct(List<ContractChange__c> newList,Map<Id,ContractChange__c>oldMap) {
        Set<Id>  ccSet= new Set<Id>();
      for (ContractChange__c cc : newList ) {
        ContractChange__c oldcc = oldMap.get(cc.Id);
        if (oldcc.Status__c != '审批成功' && cc.Status__c == '审批成功') {
            ccSet.add(cc.Id);  
        }
      }
     

      List<ContractChangeList__c> cclList =[select Id, AdjustPrice__c,AddProduct__c,DelProduct__c,ContractProduct__c, 
        Product__c,AdjustSalesPrice__c,SalesPrice__c,ContactChange__c,ContactChange__r.Contact__c,Product__r.Name,
        Product__r.Category1__c,ContactChange__r.Contact__r.CompanyControls__c,DiscountRate__c
       from ContractChangeList__c where ContactChange__c in:ccSet ]; 


       Map<Id,Id> addMap = new Map<Id,Id>();
       Set<String> companys = new Set<String>();
       for ( ContractChangeList__c ccl : cclList) {
        if (ccl.AddProduct__c == true ) {
            addMap.put(ccl.Product__c,ccl.ContactChange__r.Contact__c);
            companys.add(ccl.ContactChange__r.Contact__r.CompanyControls__c);
        }
       }
       ///查询价格
       Map<Id,Price__c> priceMap = getPriceMap(addMap.keySet(),companys);

      ///新增
      List<ContractProduct__c>cclNewList = new List<ContractProduct__c>();
      ///删除
      List<ContractProduct__c>cclDelList = new List<ContractProduct__c>();

      ///调价
      List<ContractProduct__c>cclAdjustList = new List<ContractProduct__c>();
       ///记录调价的 合同产品
       Map<Id,Decimal> productMap= new Map<Id,Decimal>();            
       Id rt  = Utils.getRecordTypeIdByDevNameAndObjName('ContractCommodityProduct','ContractProduct__c');                                   
      ///查询 合同变更明细
      for (ContractChangeList__c ccl:cclList) {
         if (ccl.AddProduct__c == true) {
             ContractProduct__c cp = new ContractProduct__c(
                    Name = ccl.Product__r.Name,
                    Product__c = ccl.Product__c,
                    AreaDealerPrice__c = priceMap.containsKey(ccl.Product__c) ? priceMap.get(ccl.Product__c).AreaDealerPrice__c : 0,
                    InvoiceDealerPrice__c = priceMap.containsKey(ccl.Product__c) ? priceMap.get(ccl.Product__c).InvoiceDealerPrice__c : 0,
                    UnitPrice1__c = priceMap.containsKey(ccl.Product__c) ? priceMap.get(ccl.Product__c).MarketPrice__c : 0,//市场报价
                    SalesPrice__c =ccl.SalesPrice__c,
                    Taxrate__c =priceMap.containsKey(ccl.Product__c) ? priceMap.get(ccl.Product__c).Taxrate__c : null ,
                    Contract__c = ccl.ContactChange__r.Contact__c,
                    ProductLine__c = ccl.Product__r.Category1__c,
                    RecordTypeId = rt,
                    DiscountRate__c =  ccl.DiscountRate__c,
                    DelContractProduct__c = false,
                    IsSycToNc__c = false

             );
             cclNewList.add(cp);
             
         }

         if (ccl.AdjustPrice__c == true) {
             ContractProduct__c cp = new ContractProduct__c(
              Id = ccl.ContractProduct__c,
              SalesPrice__c = ccl.AdjustSalesPrice__c,
              DelContractProduct__c = false,
                    IsSycToNc__c = false

             );
             cclAdjustList.add(cp);
             productMap.put(ccl.Product__c ,ccl.AdjustSalesPrice__c);
         }

         if (ccl.DelProduct__c == true) {
              ContractProduct__c cp = new ContractProduct__c(
              Id = ccl.ContractProduct__c,
              DelContractProduct__c = true

             );
              cclDelList.add(cp);
         }  
       } 

        ///记录如果是分子机构 总部
      Map<Id,Id>  DSFMap= new Map<Id,Id>();
      List<ContractProduct__c> fenfaList = new List<ContractProduct__c>();

      for(ContractChange__c cc:[select Id, Contact__r.Account__r.AccountNumber,Contact__r.Account__c from  ContractChange__c where Id in:ccSet]){
           if(cc.Contact__r.Account__r.AccountNumber != null && cc.Contact__r.Account__r.AccountNumber.contains('DSF'))DSFMap.put(cc.Id,cc.Contact__r.Account__c);
      }
      if(DSFMap.keySet().size() > 0){

      ///找到总部对应的分子机构
            Map<Id,Id>  accMap= new Map<Id,Id>();
            for(Account acc :[select Id,ParentId from Account where ParentId in:DSFMap.values()]){
                if(getKey(DSFMap,acc.ParentId) != null )accMap.put(getKey(DSFMap,acc.ParentId), acc.Id);
            }
            ///找到各个分子机构 对应的合同
            Map<Id,Id>  conMap= new Map<Id,Id>();
            Set<Id>  conSet= new Set<Id>();
            for (Contract__c con  :[select Id ,Account__c from Contract__c where Account__c in:accMap.keySet() and Stopped__c != true and  Status__c = '已生效' order by CreatedDate desc ]) {
                if(getKey(accMap,con.Account__c)!=null && !conSet.contains(con.Id)){
                    conSet.add(con.Id);
                    conMap.put(getKey(accMap,con.Account__c),con.Id);
                }
            }
            ///找到需要分发的合同产品
             for(ContractProduct__c cp : [select Id ,SalesPrice__c ,Product__c,IsSycToNc__c from ContractProduct__c where Product__c in:productMap.keySet() and Contract__c in:conMap.values()]){
                if(productMap.containsKey(cp.Product__c)){
                  cp.SalesPrice__c = productMap.get(cp.Product__c);
                  cp.IsSycToNc__c = false;
                  fenfaList.add(cp);
                }
             }

      }

      



       SavePoint sp = Database.setSavepoint();
       try {
        System.debug('==='+cclAdjustList );
          if (cclNewList.size() > 0) insert cclNewList;
          if (cclDelList.size() >0) update cclDelList;
          if (cclAdjustList.size() > 0) update cclAdjustList; 
          if(fenfaList.size() > 0) update fenfaList; 
       }catch (Exception e) {
          Database.rollback(sp); 
           System.debug('==='+e.getMessage());
       }

    }
     private static Map<Id,Price__c> getPriceMap(Set<Id> pids ,Set<String>coms){
      Map<Id, Price__c> priceMap = new Map<Id, Price__c>();
            for (Price__c pr : [select Id, Product__c,Product__r.bggsjhdj__c, MarketPrice__c, HospitalManagerPrice__c, HospitalBottomPrice__c, CompanyBottomPrice__c,
                AreaDealerPrice__c, InvoiceDealerPrice__c, RepairCost__c, InstCost__c ,LastMonthAveragePrice__c,Taxrate__c  
                                from Price__c where Product__c in : pids and Company__c in:coms]) {
                priceMap.put(pr.Product__c, pr);
            }
      return priceMap;
    }
      private static Id getKey(Map<Id,Id> m , Id obj ){

           for (Id o : m.keySet()) {
              if(obj == m.get(o))return o ;
           }
           return null;
      }
  
  */

  ///更新总部的合同产品
  /**
    acc  机构总部id 
    cpList  机构变更的合同产品列表
  */
    /*
  public static void updateSystemContractProduct(String acc,List<ContractProduct__c> cpList){

    ///找到 总部下的有效的合同 及合同产品
    Contract__c con = null;
    con = [select Id from Contract__c where Account__c =:acc and Status__c = '已生效' and Stopped__c != true Order by CreatedDate desc limit 1];
    if(con == null) return;
    Map<Id,ContractProduct__c> cpMap = new Map<Id,ContractProduct__c>();
    for (ContractProduct__c cp:[select Id,Product__c,SalesPrice__c,DelContractProduct__c from ContractProduct__c where Contract__c =:con.Id] ) {
      cpMap.put(cp.Product__c, cp);
    }

    List<ContractProduct__c> updateList  = new List<ContractProduct__c>();
    ///匹配 合同变更的产品 在总部中的 合同产品 如有有则更新 没有则新增
    for (ContractProduct__c cp: cpList) {
        
        if(cpMap.containsKey(cp.Product__c)){

          
            ContractProduct__c sysCp = cpMap.get(cp.Product__c);
            sysCp.SalesPrice__c = cp.SalesPrice__c;
            sysCp.DelContractProduct__c = cp.DelContractProduct__c;
            updateList.add(sysCp);
          
        }else{
            if(cp.DelContractProduct__c == false)continue;
                ContractProduct__c cp1 = new ContractProduct__c(
                    Name = cp.Name,
                    Product__c = cp.Product__c,
                    AreaDealerPrice__c = cp.AreaDealerPrice__c,
                    InvoiceDealerPrice__c = cp.InvoiceDealerPrice__c,
                    UnitPrice1__c = cp.UnitPrice1__c,
                    SalesPrice__c =cp.SalesPrice__c,
                    Taxrate__c = cp.Taxrate__c,
                    Contract__c = con.Id,
                    ProductLine__c =cp.ProductLine__c,
                    RecordTypeId = cp.RecordTypeId,
                    DiscountRate__c =  cp.DiscountRate__c,
                    InstCost__c = cp.InstCost__c,
                    DelContractProduct__c = false

                );
             updateList.add(cp1);

        }
    }

    if(updateList.size() > 0)upsert updateList;

  }*/
}